package com.sbl.bajw.pc.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sbl.bajw.common.DbManager;
import com.sbl.bajw.common.MyBatisDao;
import com.sbl.bajw.common.web.MessageException;
import com.sbl.bajw.common.web.RequestUnit;
import com.sbl.bajw.common.web.SessionUnit;
import com.sbl.bajw.common.web.WebContext;
import com.sbl.bajw.mapper.UserDao;
import com.sbl.bajw.pc.model.UserGpsModel;
import com.sbl.bajw.pc.model.UserModel;
import com.sbl.bajw.util.FileUpload;
import com.sbl.bajw.util.LogUtil;

@Service
public class UserService {
	
	@Resource
	private UserDao dao;
	
	static HashMap<String,UserGpsModel> userGpsModelMap = new HashMap<String, UserGpsModel>();

	static Logger log;
	
	static Logger gpsLog = null;
	
	static{
		log = LogUtil.getLogger("userlog");
	}
	
	static{
		gpsLog = LogUtil.getLogger("gpsLog");
	}
	
	@Resource 
	private MyBatisDao gridDao;
	
	/**
	 * @作者：罗琦
	 * @return 获取用户GPS接口（APP）
	 */
	public List<HashMap<String, Object>> getUserGpsList(){
		List<HashMap<String, Object>> list= dao.getUserGpsList();
		return list;
	}
	
	public UserModel getModelByName(String username){
		if(username == null || username.equals("") )
		{
			return null;
		}
		UserModel model = dao.getModelByName(username);
		return model;
	}
	
	public void update(UserModel user){
		dao.update(user);
	}
	
	public UserModel getModel(String id){
		HashMap<String, String> parm = new HashMap<String, String>();
		parm.put("userid", id);
		UserModel model = dao.getModel(id);
		return model;
	}
	
	public UserModel getModelWithGpsInfo(String id){
		HashMap<String, String> parm = new HashMap<String, String>();
		parm.put("userid", id);
		UserModel model = dao.getModelWithGpsInfo(id);
		return model;
	}
	
	public HashMap<String, Object> getUserModel(String id){
		HashMap<String, Object> list = dao.getUserModel(id);
		return list;
	}
	
	public UserModel createModel(String username,String password){
		UserModel model = new UserModel();
		String id = dao.getId();
		model.setId(id);
		model.setUsername(username);
		model.setPassword(password);
		model.setImageurl("/images/nohead.png");
		dao.insert(model);
		return model;
	}
	
	public void updateUserGps(UserModel model){
		UserGpsModel userGpsModel = getUserGpsModel(model.getId());
		userGpsModel.add(model.getGpsX(), model.getGpsY(),model.getGpsSpeed());
		if(model.getGpsX() < 10 || model.getGpsY() < 10 ){
			model.setGpsX(null);
			model.setGpsY(null);
		}
		dao.update(model);
		if(userGpsModel.getGpsCount() > 5){
			dao.insertUserGps(userGpsModel);
			userGpsModel.clear();
			gpsLog.info(userGpsModel.getUserid()+" gps数据入库");
		}
	}
	
	public String getUserList(HashMap<String, Object> parm){
		String list = gridDao.selectPage(UserDao.class, parm, "getModelList");
		return list;
	}
	
	public List<HashMap<String, Object>> getModelList(HashMap<String, Object> parm){
		List<HashMap<String, Object>> list = dao.getModelList(parm);
		return list;
	}
	
	public String getLocalhostModelList(HashMap<String, Object> parm){
		String list = gridDao.selectPage(UserDao.class, parm, "getLocalhostModelList");
		return list;
	}
	
	public HashMap<String, Object> getCount(){
		HashMap<String, Object> map = dao.getCount();
		return map;
	}
	
	public void insertUserGps(UserGpsModel model){
		dao.insertUserGps(model);
	}
	
	public UserGpsModel getUserGpsModel(String userid){
		UserGpsModel model = userGpsModelMap.get(userid);
		if(model == null){
			model = new UserGpsModel(userid);
			userGpsModelMap.put(userid, model);
		}
		return model;
	}
	
	public List<HashMap<String, Object>> getHistoryPoition(HashMap<String, Object> parm){
		List<HashMap<String, Object>> models = dao.getHistoryPoition(parm);
		return models;
	}
	
	public int isUserThere(HashMap<String, String> parm){
		int num = dao.isUserThere(parm);
		return num;
	}
	
	@Transactional(readOnly = false)
	public void register(UserModel user) throws Exception{
		HashMap<String, String> parm = new HashMap<String, String>();
		parm.put("name", user.getUsername());
		int num = isUserThere(parm);
		if(num > 0){
			throw new MessageException("用户名已存在");
		}
		
		List<HashMap<String, Integer>> jwtUserIds = dao.getPersonId(user.getUsername());
		
		if(jwtUserIds.size() >=1){
			throw new MessageException("用户名已存在");
		}
		
		String id = dao.getId();
		user.setId(id);
		user.setImei(user.getUsername());
		user.setImageurl("/images/nohead.png");
		dao.insert(user);
		insertEquipment(user);
		insertPersons(user);
		insertEquipmentffPerson(user);
		SessionUnit.setUserId(user.getId() + "");
		SessionUnit.setUserName(user.getShowname());
	}
	
	public void updateApp(UserModel model){
		model.setUsername(null);
		dao.update(model);
	}
	
	public void insertEquipment(UserModel user) throws Exception{
		
		String sql = "insert into equipment@ysdblink(equipmentid,equipmentcode,equipmenttypeid,departmentid,imeinum,mobilephone,storestatuscode,usestatuscode,createtime)"
		 +"values(seq_equipment.nextval@ysdblink,?,?,?,?,?,?,?,sysdate)";
		
		List<String> parm = new ArrayList<String>();
		parm.add(user.getTelNumber());
		parm.add("64");
		parm.add("516");
		parm.add(user.getUsername());
		parm.add(user.getTelNumber());
		parm.add("3");
		parm.add("3");
		
		DbManager.executeUpdate(sql, parm);
		DbManager.commit();
	}
	
	public void insertPersons(UserModel user) throws Exception{
		
		String sql = "insert into persons@ysdblink(personid,personcode,name,departmentid,persontypeid,createtime) "
		+" values(seq_persons.nextval@ysdblink,?,?,?,?,sysdate)";
		
		List<String> parm = new ArrayList<String>();
		parm.add(user.getUsername());
		parm.add(user.getShowname());
		parm.add("516");
		parm.add("141");
		
		DbManager.executeUpdate(sql, parm);
		DbManager.commit();
	}
	
	public void insertEquipmentffPerson(UserModel user) throws Exception{
		
		String sql = "insert into equipmentffperson@ysdblink(id,departmentid,personid,equipmentid,createtime)"
		+" values(seq_equipmentffperson.nextval@ysdblink,?,?,?,sysdate)";
		
		List<HashMap<String, Integer>> jwtUserIds = dao.getPersonId(user.getUsername());
		Integer eid = dao.getEquipmentId(user.getUsername());
		String pid = jwtUserIds.get(0).get("PERSONID")+"";
		log.info("pid:"+pid);
		List<String> parm = new ArrayList<String>();
		parm.add("516");
		parm.add(pid+"");
		parm.add(eid+"");
		
		DbManager.executeUpdate(sql, parm);
		DbManager.commit();
	}
	
	public String updateImageUrl(UserModel model) throws MessageException{
		String path = "";
		try {
			uploadFile(model);
			dao.update(model);
			path = model.getImageurl();
		} catch (Exception e) {
			e.printStackTrace();
			throw new MessageException("头像上传失败", "4");
		}
		return path;
	}
	
	public void update(String id, String pwd){
		UserModel user = new UserModel();
		user.setId(id);
		user.setPassword(pwd);
		dao.update(user);
	}
	
	public int getUserCount(HashMap<String, String> parm){
		int num = dao.getUserCount(parm);
		return num;
	}
	
	public void updatePwd(HashMap<String, String> parm){
		dao.updatePwd(parm);
	}
	
	public void updateUser(String id, String sex, String username, String phone,
			String type, String job, String mjjh, String deptfullid,String carId,String bankcardNo){
		UserModel user = new UserModel();
		user.setId(id);
		user.setSex(sex);
		user.setShowname(username);
		user.setTelNumber(phone);
		user.setUsertype(type);
		user.setUserJob(job);
		user.setDeptfullid(deptfullid);
		user.setMjjh(mjjh);
		user.setCardId(carId);
		user.setBankcardNo(bankcardNo);
		dao.update(user);
	}
	
	@Transactional(readOnly=false)
	public void insert(List<UserModel> list){
		for(int i = 0; i < list.size(); i++){
			UserModel user = list.get(i);
			dao.insert(user);
			System.out.println(user.getId());
			System.out.println(user.getUsername());
			System.out.println(user.getShowname());
			System.out.println(user.getUsertype());
			System.out.println(user.getTelNumber());
		}
	}
	
	public List<HashMap<String, Object>> getUserTeam(String id){
		List<HashMap<String, Object>> team = dao.getUserTeam(id);
		return team;
	}
	
	public String uploadFile(UserModel model) throws Exception{
		
		FileItem item = RequestUnit.getFileItem("img");
		String resultPath = "";
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmssS");
		
		if(item!=null)
		{
			String path = WebContext.getRequest().getSession().getServletContext().getInitParameter("UploadPath");
			String dataStr = sf.format(Calendar.getInstance().getTime());
			resultPath = "upload/police/"+FileUpload.saveFile(item, path+"/upload/police/",dataStr+"_"+model.getId());
			log.info(model.getId()+"图片上传成功:"+resultPath);
			model.setImageurl(resultPath);
		}
		else{
			log.info(model.getId()+"没有图片数据");
		}
		return resultPath;
	}
}
